<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.company_id"
        :placeholder="$t('table.company')"
        style="width:120px"
        clearable
        size="small"
        @change="handleFilterone(listQuery.company_id)"
      >
        <el-option
          v-for="(item, index) in companylist"
          :key="index"
          :label="item.company"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-model="listQuery.department_id"
        :placeholder="$t('table.department')"
        style="width:120px"
        clearable
        size="small"
        @change="handleFilter"
      >
        <el-option
          v-for="(item, index) in department_list"
          :key="index"
          :label="item.department"
          :value="item.id"
        />
      </el-select>
      <el-input
        v-model="listQuery.person_id"
        :placeholder="$t('table.worker_id')"
        size="small"
        style="width: 200px;"
        clearable
        @change="handleFilter"
      />
      <el-input
        v-model="listQuery.name"
        :placeholder="$t('table.worker_name')"
        size="small"
        style="width: 200px;"
        clearable
        @change="handleFilter"
      />
      <el-date-picker
        v-model="listQuery.time"
        :start-placeholder="$t('table.start_time')"
        :end-placeholder="$t('table.end_time')"
        type="datetimerange"
        size="small"
        value-format="yyyy-MM-dd"
        range-separator="一"
        format="yyyy-MM-dd"
        @change="handleFiltertime"
      />
      <el-button type="primary" size="small" @click="getLists">{{
        $t("table.search")
      }}</el-button>
      <el-button type="primary" size="small" @click="getExcel">{{
        $t("table.export")
      }}</el-button>
      <summary />
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="{
        background: '#f2f2f2',
        color: '#606266',
        height: '10px',
        padding: '5px'
      }"
      :row-style="{ height: '40px', padding: '0px' }"
      :cell-style="{ padding: '0px' }"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      height="660px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column :label="$t('table.avatar')" align="center">
        <template slot-scope="scope">
          <img
            :src="base64Prefix + scope.row.now_img"
            style="width: auto;height: 80px;border: 0;"
            @click="bigImg(scope.row.id)"
          >
          <transition name="el-zoom-in-top">
            <div
              v-show="scope.row.id === listItemId"
              class="bigImg"
              @click="bigImg"
            >
              <img :src="base64Prefix + scope.row.now_img" >
            </div>
          </transition>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.worker_id')"
        :render-header="labelHead"
        class-name="status-col"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.person_id != '-1'">{{
            scope.row.person_id
          }}</span>
          <span v-else/>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.worker_name')"
        :render-header="labelHead"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.company')"
        :render-header="labelHead"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.company }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.department')"
        :render-header="labelHead"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.department }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.device_name')"
        :render-header="labelHead"
        align="center"
      >
        <template slot-scope="scope">
          {{ scope.row.device_name }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.device_ip')" align="center">
        <template slot-scope="scope">
          {{ scope.row.ip }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.date_time')" align="center">
        <template slot-scope="scope">
          {{ scope.row.pass_ts }}
        </template>
      </el-table-column>
      <!-- <el-table-column :label="$t('table.time')" align="center">
        <template slot-scope="scope">
          {{ scope.row.pass_ts | toTime }}
        </template>
      </el-table-column> -->
      <!-- <el-table-column :label="$t('table.temperature')" align="center">
        <template slot-scope="scope">
          {{ scope.row.mapping_temp | toTemp }}
        </template>
      </el-table-column> -->
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="current_page"
        :page-sizes="[50, 100, 200]"
        :page-size="per_page"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import store from '@/store'
import { parseTime } from '@/utils/index'
import { traffic_record_get_list } from '@/api/StatisticalReports/StatisticalReports'
import { get_select } from '@/api/organization_manage/organization_manage'
import { department_get_select } from '@/api/user_manage/user_manage'

export default {
  components: {},
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      listItemId: null,
      base64Prefix: 'data:image/jpg;base64,',
      list: null,
      listLoading: true,
      total: null,
      date: null,
      multipleSelection: [],
      current_page: null,
      last_page: null,
      per_page: null,
      timeout: null,
      companylist: null,
      department_list: null,
      listQuery: {
        company_id: undefined,
        department_id: undefined,
        beginTime: undefined,
        endTime: undefined,
        name: undefined,
        time: [],
        person_id: undefined,
        page: 1,
        pagesize: 50
      }
    }
  },
  created() {
    // this.timeout = setTimeout(() => {
    //   this.getLists();
    //   console.log("2223523");
    // }, 3000);
    this.getListspos()
    const timestamp = new Date().getTime()
    this.listQuery.beginTime = this.time(timestamp - 2592000000)
    this.listQuery.endTime = this.time(timestamp)
    this.listQuery.time[0] = this.listQuery.beginTime
    this.listQuery.time[1] = this.listQuery.endTime
    console.log(this.time(timestamp), 'tttttttttttttttttt')
  },
  // destroyed: function () {
  //   clearTimeout(this.timeout);
  //   console.log("没了");
  // },
  mounted() {
    this.timeout = setInterval(() => {
      console.log('执行了222222222')
      this.getLists()
    }, 3000)
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.timeout)
    console.log('beforeDestroy')
  },
  methods: {
    time(time) {
      var date = new Date(time + 8 * 3600 * 1000)
      return date
        .toJSON()
        .substr(0, 10)
        .replace('T', ' ')
        .replace(/-/g, '-')
    },
    // 获取展示列表数据
    getListspos() {
      this.listLoading = true
      traffic_record_get_list(store.getters.token, this.listQuery).then(res => {
        console.log(res, 'res')
        this.list = res.data.list.data
        this.current_page = res.data.list.current_page
        this.per_page = res.data.list.per_page
        this.last_page = res.data.list.last_page
        this.total = res.data.list.total
        this.listLoading = false
      })
      // 获取公司数据
      get_select(store.getters.token).then(res => {
        this.companylist = res.data.list
      })
    },
    getLists() {
      traffic_record_get_list(store.getters.token, this.listQuery).then(res => {
        console.log(res, 'res')
        this.list = res.data.list.data
        this.current_page = res.data.list.current_page
        this.per_page = res.data.list.per_page
        this.last_page = res.data.list.last_page
        this.total = res.data.list.total
        this.listLoading = false
      })
      // 获取公司数据
      get_select(store.getters.token).then(res => {
        this.companylist = res.data.list
      })
    },
    bigImg(id) {
      if (id > 0) {
        this.listItemId = id
      } else {
        this.listItemId = null
      }
    },
    // 分页相关方法
    handleFilter() {
      this.listQuery.page = 1
      this.getLists()
    },
    handleFilterone(val) {
      console.log(val, 'val')
      this.listQuery.page = 1
      this.getLists()
      department_get_select(store.getters.token, { company_id: val }).then(
        res => {
          this.department_list = res.data.list
          console.log(this.department_list, 'this,department_list')
          console.log(res, 'res.data.list')
        }
      )
    },
    handleFiltertime(val) {
      this.listQuery.beginTime = val[0]
      this.listQuery.endTime = val[1]
      this.getLists()
    },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getLists()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getLists()
    },
    handleSelectionChange(val) {
      console.log(val, 'oooooooooooooooooooooo')
      this.multipleSelection = []
      val.forEach(item => {
        this.multipleSelection.push(item.device_id)
      })
    },
    // 导出报表
    getExcel() {
      const date = new Date() // 时间戳为10位需乘1000，为13位则不用
      const Y = date.getFullYear() // 年
      const M =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1 // 月
      const D =
        date.getDate() < 10 ? '0' + date.getDate() + '' : date.getDate()
      const date_time = Y + '-' + M + '-' + D
      traffic_record_get_list(store.getters.token, this.listQuery).then(res => {
        this.export = res.data.list.data
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = [
            this.$t('table.worker_id'),
            this.$t('table.worker_name'),
            this.$t('table.company'),
            this.$t('table.department'),
            this.$t('table.device_name'),
            'IP',
            this.$t('table.date')
            // this.$t('table.temperature')
          ]

          // "工号", "姓名", "公司", "部门", "设备名称", "IP", "日期", "体温";
          const filterVal = [
            'person_id',
            'name',
            'company',
            'department',
            'sn',
            'ip',
            'pass_ts'
            // 'mapping_temp'
          ]
          const list = res.data.list.data
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.$t('menu.access_records') + ' ' + date_time,
            autoWidth: true,
            bookType: 'xlsx'
          })
        })
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
          if (j === 'person_id') {
            if (v.person_id == '-1') {
              return v.person_id == ''
            } else {
              return v.person_id
            }
          }
        })
      )
    },
    labelHead(h, { column, index }) {
      const l = column.label.length
      const f = 16 // 每个字大小，其实是每个字的比例值，大概会比字体大小差不多大一点，
      column.minWidth = f * l // 字大小乘个数即长度 ,注意不要加px像素，这里minWidth只是一个比例值，不是真正的长度 //然后将列标题放在一个div块中，注意块的宽度一定要100%，否则表格显示不完全
      return h('div', { class: 'table-head', style: { width: '100%' }}, [
        column.label
      ])
    }
  }
}
</script>
<style scoped>
.app-container {
  border-top: #eee solid 10px;
}

.pagination-container {
  margin-top: 10px;
}
.pagination-container {
  margin-top: 25px;
}
.bigImg {
  min-width: 100%;
  min-height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999999;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  /*transition:1s;*/
}
.bigImg img {
  max-width: 650px;
  min-width: 235px;
}
</style>
